package com.company.project.learning.thread.Demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhaoqi
 * @Date: 11/22/2019 10:16 PM
 * @Version 1.0
 */
//两个线程交替打印奇偶数1-100 ReentrantLock 普通创建线程

public class TwoThread {

    private int start = 0;

    private boolean flag =false;

    private final static Lock lock = new ReentrantLock();

    public static void main(String[] args) {

        TwoThread twoThread = new TwoThread();
        Thread thread1 = new Thread(new OuNum(twoThread));
        Thread thread2 = new Thread(new JiNum(twoThread));
        thread1.setName("s1");
        thread2.setName("s2");
        thread1.start();
        thread2.start();

    }

    public static class OuNum implements Runnable{

        private TwoThread number;

        public OuNum(TwoThread number) {
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start <=100){
                if (number.flag){
                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + "--------------" + number.start);
                        number.start++;
                        number.flag =false;
                    }finally {
                        lock.unlock();
                    }
                }else {
                    //防止线程空转
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static class JiNum implements Runnable{

        private TwoThread number;

        public JiNum(TwoThread number) {
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start <=100){
                if (!number.flag){
                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + "++" + number.start);
                        number.start++;
                        number.flag =true;
                    }finally {
                        lock.unlock();
                    }
                }else {
                    //防止线程空转
                    try {
                        Thread.sleep(10);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
